import os
import json
import csv
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime


def parse_and_save(root, filename):
    listdir = os.listdir(root)
    cnt = 0
    result = {}

    for file in listdir:
        with open(os.path.join(root, file), 'r', encoding='utf-8') as f:
            datas = json.load(f)

            # print(datas.keys())
            # # ['msg', 'code', 'data']
            #
            # print(datas['data'].keys())
            # # ['last_rid', 'create_list', 'account_id',
            # # 'del_list', 'update_list', 'record_sync_time']
            #
            # print(datas['data']['create_list'][0].keys())
            # # ['asset_id', 'week', 'server_id', 'uid', 'book_name',
            # # 'cid', 'remark', 'record_images', 'is_auto', 'category_type',
            # # 'client_id', 'icon_name', 'book_id', 'icon_url', 'date',
            # # 'sort_time', 'amount', 'category_id', 'category_name']

            create_list = datas['data']['create_list']
            for data in create_list:
                result[cnt] = {
                    'date': data['date'],
                    'week': data['week'],
                    'category_id': data['category_id'],
                    'category_name': data['category_name'],
                    'amount': data['amount'],
                    'remark': data['remark']
                }
                cnt += 1
    # print(result)
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(result, f)


def json2csv(path, filename):
    with open(path, 'r', encoding='utf-8') as f:
        datas = json.load(f)

    header = list(datas['0'].keys())

    with open(filename, 'w', encoding='utf-8', newline='') as f:
        writer = csv.DictWriter(f, header)
        writer.writeheader()
        writer.writerows(datas.values())


def draw_bar(path, remark):
    with open(path, 'r', encoding='utf-8', newline='') as f:
        reader = csv.DictReader(f)
        df = pd.DataFrame(reader)

        # print(df[df['remark'] == remark])
        date = df[df['remark'] == remark]['date'].map(lambda x: datetime.strptime(x, '%Y年%m月%d日'))
        amount = df[df['remark'] == remark]['amount']
        amount = [float(a) for a in amount]
        # print(list(date), amount)

        plt.bar(list(date), amount)
        plt.xticks(rotation=-45)
        plt.show()


if __name__ == '__main__':
    root = 'datas'
    parse_and_save(root, 'result.json')
    json2csv('result.json', 'result.csv')
    draw_bar('result.csv', '麦当劳')
